import { createRouter, createWebHistory } from 'vue-router'

import AllRoomType from '@/views/AllRoomType.vue'
import BaseRoomType from '@/views/BaseRoomType.vue'
import MainPage from '../views/MainPage.vue'
import Skeleton from '../views/Skeleton.vue'
// import HomePage from '../views/HomePage.vue'
import DetailPage from '@/views/DetailPage.vue'
import BookRoomPage from '@/views/BookRoomPage.vue'

import api from '@/api/index.js';
import { userStore } from '@/stores/userInfoStore.js';

// 定义路由
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [

    //默认路径
    {
      path: '/',
      name: 'RootRedirect',
      redirect: '/index' // 重定向到默认子路由
    },

    // 首页
    {
      path: '/index',
      name: 'Skeleton',
      component: Skeleton,
      // 嵌套路由
      children: [ 
        // 例如，一个指向特定详情页面的嵌套路由
        { path: '', name: 'MainPage', component: MainPage, meta: { activeMenu: '0' } }, // 这里使用空字符串表示这是默认子路由
      ]
    },

    // 房间页面
    {
      path: '/room',
      name: 'room',
      component: Skeleton,
      // 嵌套路由
      children: [ 
        // 例如，一个指向特定详情页面的嵌套路由
        { path: 'AllRoomType', name: 'AllRoomType', component: AllRoomType, meta: { activeMenu: '1' } },
        { path: 'DetailPage', name: 'DetailPage', component: DetailPage, meta: { activeMenu: '2' } },
        { path: 'BookRoomPage', name: 'BookRoomPage', component: BookRoomPage, meta: { activeMenu: '3' } },
        
      ]
    },
    

    // 个人信息页面
    {
      path: '/personal',
      name: 'Personal',
      component: () => import('@/views/personal.vue'),
      children: [
        {path: 'personalInfo',name: 'personalInfo', component: () => import('@/components/PersonalInfo.vue')},
        {path: 'personalComment',name: 'personalComment', component: () => import('@/components/PersonalComment.vue')},
        {path: 'personalOrders',name: 'personalOrders', component: () => import('@/components/PersonalOrders.vue')}
      ]
    },

    // 个人订单
    {
      path:'/allPersonalOrders',
      name: 'allPersonalOrders',
      component: () => import('@/views/allPersonalOrders.vue')
    }

  ],
  //路由跳转自动滚动到顶部
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } 
    return { top: 0 };
  }
})





// 注册全局前置守卫
router.beforeEach(async(to, from, next) => {
  const userStoreInfo = userStore()

  // 如果是默认页，直接放行
  if((to.path==='/index') && localStorage.getItem('ruiYaUserLoginToken') == null){
    next();
  }

  else{
    await api.ParseJwt(localStorage.getItem('ruiYaUserLoginToken')).then(res=>{
      if(res.data.code == 0){
        console.log('解析错误',res.data.msg)
        alert('身份验证失败，请重新登录')
        next('/index'); // 取消导航，重定向到index页面
      }else{
        next();
        userStoreInfo.setUserInfo(res.data.data)
        //console.log("userStoreInfo为",userStoreInfo.userInfo)
      }
    }).catch(err=>{
      console.log('错误原因为：',err)
    })
  }
    
}) 
export default router